package api

import (
	"context"
	"fmt"
	"go_final/mxshop_api/user_web/forms"
	"go_final/mxshop_api/user_web/global"
	"math/rand"
	"net/http"
	"strings"
	"time"

	"go.uber.org/zap"

	"github.com/go-redis/redis/v8"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"

	"github.com/gin-gonic/gin"
)

// GenerateSMSCode 生成长度为length的随机数
func GenerateSMSCode(length int) string {
	numeric := [10]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	r := len(numeric)
	rand.Seed(time.Now().UnixNano())

	var sb strings.Builder

	for i := 0; i < length; i++ {
		fmt.Fprintf(&sb, "%d", numeric[rand.Intn(r)])
	}
	return sb.String()
}

func SendSMS(c *gin.Context) {
	sendSmsForm := forms.SendSMSForm{}
	if err := c.ShouldBind(&sendSmsForm); err != nil {
		HandleValidateError(c, err)
		return
	}

	client, err := dysmsapi.NewClientWithAccessKey("ap-northeast-1", global.ServerConfig.AliSMSConfig.Apikey,
		global.ServerConfig.AliSMSConfig.ApiSecret)
	if err != nil {
		panic(err)
	}

	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = "https"

	request.PhoneNumbers = sendSmsForm.Mobile
	request.SignName = "帮福共享科技"
	request.TemplateCode = "SMS_173150562"
	// request.TemplateParam = "{\"code\":\"1111\"}"
	smsCode := GenerateSMSCode(4)
	request.TemplateParam = fmt.Sprintf(`{"code":"%s"}`, smsCode)

	response, err := client.SendSms(request)
	if err != nil {
		fmt.Print(err.Error())
	}
	fmt.Printf("response is %#v\n", response)

	// 保存验证码到redis中
	rdb := redis.NewClient(&redis.Options{
		Addr:     fmt.Sprintf("%s:%d", global.ServerConfig.RedisInfo.Host, global.ServerConfig.RedisInfo.Port),
		Password: "123456", // no password set
	})

	err = rdb.Set(context.Background(), sendSmsForm.Mobile, smsCode, time.Duration(global.ServerConfig.RedisInfo.Expire)*time.
		Second).Err()
	if err != nil {
		zap.S().Info("生成验证码失败", err.Error())
	}

	c.JSON(http.StatusOK, gin.H{
		"msg": "验证码发送成功",
	})
}
